package setting

import (
	wechat_official_account_openid_model "code.gitea.io/gitea/models/wechat"
	"code.gitea.io/gitea/modules/log"
	gitea_web_context "code.gitea.io/gitea/services/context"
	wechat_official_account_cache_service "code.gitea.io/gitea/services/wechat/cache"
	wechat_official_account_service "code.gitea.io/gitea/services/wechat/official_account"
)

// BindWechatOfficialAccountQR 将二维码扫描人 OpenID 关联到数据库用户中
func BindWechatOfficialAccountQR(ctx *gitea_web_context.Context) {

	// 1. 取出 微信公众号二维码 ticket
	wechatQrTicket := ctx.Base.Req.URL.Query().Get("ticket")

	// 2. 取出用户openid并清空对应的ticket
	qrStatusVO, err := wechat_official_account_service.GetTempQRStatus(wechatQrTicket)
	if err != nil {
		log.Error("绑定微信失败: " + err.Error())
		ctx.Flash.Error("绑定微信失败：" + err.Error())
		ctx.Redirect("/user/settings/account")
		return
	}
	_ = wechat_official_account_cache_service.DeleteWechatOfficialAccountQrByTicket(wechatQrTicket)

	// 3. 从 Gitea Web Context 中获取用户信息
	user := ctx.Doer

	// 4. 更新数据库 `user_wechat_official_account_openid`
	err = wechat_official_account_openid_model.UpdateOrCreateWechatOfficialAccountUser(ctx, user, qrStatusVO.OpenId)
	if err != nil {
		log.Error("绑定微信失败: " + err.Error())
		ctx.Flash.Error("绑定微信失败: " + err.Error())
		ctx.Redirect("/user/settings/account")
		return
	}

	// 5. 携带扫码成功信息，重定向回用户修改信息页面
	ctx.Data["wechatOfficialAccountQRScanSuccess"] = true
	Account(ctx)
}

// UnbindWechatOfficialAccountQR 解绑微信
func UnbindWechatOfficialAccountQR(ctx *gitea_web_context.Context) {
	_ = wechat_official_account_openid_model.DeleteWechatOfficialAccountUser(ctx, ctx.Doer)
	ctx.Flash.Success(ctx.Tr("settings.wechat_official_account_unbind_success"))
	ctx.Redirect("/user/settings/account")
}
